//
//  YDYCommentViewController.m
//  DYSisterAPP
//
//  Created by 杨德勇 on 2016/8/9.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "YDYCommentViewController.h"
#import "YDYRefreshHeader.h"
#import "YDYRefreshFooter.h"
#import "YDYHTTPSessionManager.h"
#import "YDYTopic.h"
#import "YDYComment.h"
#import <MJExtension.h>
#import "YDYCommentCell.h"
#import "YDYTopicCell.h"
#import "YDYTopic.h"
@interface YDYCommentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomMargin;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** httpmaneger */
@property (nonatomic, strong) YDYHTTPSessionManager *manager;
/** 最热评论 */
@property (nonatomic, strong) NSArray<YDYComment *> *hotestComments;
/** 最新评论 */
@property (nonatomic, strong) NSMutableArray<YDYComment *> *latestComments;

/** 用于记录修改了topic数据待会改回去 */
@property (nonatomic, strong) YDYComment  *savedTop_cmt;
@end

@implementation YDYCommentViewController


#pragma mark -
#pragma mark -cellid


static NSString * const  ydyCommentCellID = @"comment";

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置默认的东西
    [self setupDefault];
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YDYCommentCell class]) bundle:nil  ] forCellReuseIdentifier:ydyCommentCellID];
    //设置上拉和下拉刷新
    [self setupRefresh];
    //第一次加载数据
    [self loadNewComments];
    //设置显示原来的帖子内容
    [self setupHeader];
    
    
}
-(void)setupHeader{
    //修改模型
    self.savedTop_cmt = self.topic.top_cmt;
    
    self.topic.top_cmt = nil;
    //设置高度为0，这样调用height的get方法的时候回重新算
    self.topic.cellHeight = 0;
    
    
    UIView *header = [[UIView alloc]init];
    YDYTopicCell *cell = [YDYTopicCell ydy_viewfromXib];
    cell.topic = self.topic;
    //在cell的内部有拦截frame的修改，注意不要多次修改frame
    cell.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.topic.cellHeight);
    [header addSubview:cell];
    //设置header的高度(cell的高度),后面+10 是因为cell的Y值被增加了10，
    header.ydy_height = cell.ydy_height + 10 ;
    
    self.tableView.tableHeaderView = header;
}

-(void)setupDefault{
    self.navigationItem.title = @"评论";
    self.tableView.backgroundColor = [UIColor grayColor];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    //tableview
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200;
}

-(void)setupRefresh{
    //下拉刷新
    self.tableView.mj_header = [YDYRefreshHeader headerWithRefreshingTarget:self   refreshingAction:@selector(loadNewComments)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //上拉刷新
    self.tableView.mj_footer = [YDYRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComments)];
}

#pragma mark -
#pragma mark -网络请求

-(void)loadNewComments{
    //刷新底部footerview的状态
    [self.tableView.mj_footer resetNoMoreData];
    //取消所有网络请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    //请求体
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"]= @"datalist";
    params[@"c"]= @"comment";
    params[@"data_id"] = self.topic.ID;
    params[@"hot"] = @"1";
    
    //发送请求
    __weak typeof (self) weakself = self;
    [self.manager GET:YDYcommentURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        YDYWriteToPlist(responseObject, @"comment");
        
        //字典转模型r
        weakself.latestComments = [YDYComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        weakself.hotestComments = [YDYComment mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        //刷新数据
        [self.tableView reloadData];
        //停止控件
        [self.tableView.mj_header endRefreshing];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YDYLog(@"%@",error);
         [self.tableView.mj_header endRefreshing];
    }];
    
    
}
-(void)loadMoreComments{
  
    
    //取消所有网络请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    //请求体
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"]= @"datalist";
    params[@"c"]= @"comment";
    params[@"data_id"] = self.topic.ID;
    params[@"lastcid"] = self.latestComments.lastObject.ID;
    
    //发送请求
    __weak typeof (self) weakself = self;
    [self.manager GET:YDYcommentURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        YDYWriteToPlist(responseObject, @"comment");
        
        //字典转模型
        NSArray * moreComments = [YDYComment mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakself.latestComments addObjectsFromArray:moreComments];
        //刷新数据
        [self.tableView reloadData];
        //判断全部数据是否加载完成
        int total = [responseObject[@"total"] intValue];
        if (weakself.latestComments.count == total) {
            //说明已经全部加载完成
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        //停止控件
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YDYLog(@"%@",error);
         [self.tableView.mj_header endRefreshing];
    }];
}


#pragma mark -
#pragma mark -dealloc
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark -监听
-(void)keyboardWillChangeFrame:(NSNotification *)note{
    
    //修改约束
    CGFloat keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    self.bottomMargin.constant = [UIScreen mainScreen].bounds.size.height - keyboardY;
    
    //动画
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}

#pragma mark -
#pragma mark -tableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //有最热评论
    if (self.hotestComments.count)return 2;
    //只有最新
    if (self.latestComments.count)return 1;
    
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 && self.hotestComments.count) {
        return self.hotestComments.count;
    }else{
        return self.latestComments.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    YDYCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:ydyCommentCellID];
    if (indexPath.section == 0 && self.hotestComments.count) {
        cell.comment = self.hotestComments[indexPath.row];
    }else{
        cell.comment = self.latestComments[indexPath.row];
    }
    
    
    cell.comment = self.latestComments[indexPath.row];
    
    return cell;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0 && self.hotestComments.count) {
        return @"最热评论";
    }else{
        return @"最新评论";
    }

            
    
}
#pragma mark -
#pragma mark -tableview delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIButton *btn = [[UIButton alloc]init];
    btn.titleLabel.font = [UIFont systemFontOfSize:20];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor grayColor];
    if (section == 0 && self.hotestComments.count) {
        
        [btn setTitle:@"最热评论" forState:UIControlStateNormal];
        
    }else{
        
         [btn setTitle:@"最新评论" forState:UIControlStateNormal];
         
    }
    

    return btn;
}
#pragma mark -
#pragma mark -懒加载
-(YDYHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [[YDYHTTPSessionManager alloc]init];
    }
    return  _manager;
}
@end
